<?php
/**
 * 天马供应商SDK
 * @author 陈韵
 */
namespace App\Service\VendorClient\Shoptianma;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use Hyperf\Utils\WaitGroup;

class ShoptianmaApiClient
{
    private $account  = 'Shoptianma';
    protected $config;
    protected $RouteMap = [
        'queryGoodsList'        => '/api/openapi/getCommodityList.do',
        'queryGoodsDetail'      => '/api/openapi/queryProductInfo.do',
        'queryBarcode'          => '/api/openapi/queryBarcodes.do',
        'queryInventoryList'    => '/api/openapi/getInventoryListByGroup.do',
        'createOrder'           => '/api/openapi/setOrderInfos.do',
        'queryOrder'            => '/api/openapi/getOrderInfo.do',
        'applyCancelOrder'      => '/api/openapi/applyCancel.do',
        'addAfterSalesOrder'    => '/api/openapi/addAfterSales.do',
        'getOrderFeedBackList'  => '/api/openapi/getOrderFeedBackList.do',
    ];
    

    public function __construct($apiBody = []){
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
/**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo1");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        $supplier_map_list = $params['supplier_map_list'];
        $warehouse_name = '';
        $delivery       = '';
        $goods_info    = [];

        //获取下单商品信息
        foreach ($params['orderGoods'] as $key => $item )
        {
            //商品组
            if(empty($supplier_map_list[$item['supplier_skuid']])){

                return Normal::returnCode(Normal::FAIL,"供应商商品ID".$item['supplier_skuid']."数据不存在，请核实！");
            }

            $supplierInfo   = $supplier_map_list[$item['supplier_skuid']];
            // 仓库名字
            $warehouse_name = $supplierInfo['DefaultStock'];
            //发货方式
            $delivery       = $supplierInfo['DeliveryMethod'];

            $spec           = json_decode($supplierInfo['SupplierCommoditySpec'],true);
            if(!isset($spec[0]["spec_value"]) or empty($spec[0]["spec_value"])){
                return Normal::returnCode(Normal::FAIL,"供应商商品{$supplierInfo['SupplierCommodityKey']}规格属性为空，请核实！");
            }
            
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            
            $goods_info[]= [
                'goods_no'     => (string)$supplierInfo['SupplierCommodityKey'],
                'size'         => (string)$spec[0]["spec_value"],
                'amount'       => $buyAcount,
            ];
        }
        
        $orders_info = [[
            'order_sn'          => $orderInfo['supplier_dsn'],
            'name'              => $orderInfo["receive_name"],
            'mobile'            => $orderInfo["recveive_phone"],
            'address'           => $orderInfo["receive_address"],
            'province'          => $orderInfo["province"],
            'city'              => $orderInfo["city"],
            'area'              => $orderInfo["district"],
            'delivery'          => $delivery,
            'warehouse_name'    => $warehouse_name,
            'buyer_remark'      => $orderInfo['order_remark']??"尽快发货",
            'goods_info'        => $goods_info,
        ]];
        //创建订单数据
        $data = [
            'sign'          => $this->config['sign'],
            'name'          => $this->config["account"],
            'pwd'           => $this->config["password"],
            'orders_info'   => json_encode($orders_info,JSON_UNESCAPED_UNICODE),
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data,
        ];
        $res  = $this->createOrderExecute($requestParam);
        if( $res['code'] == Normal::SUC ) {
            $thirdpart_order_sn =  $res["data"][0]["orders"][0]["order_id"];
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $thirdpart_order_sn
            ]);
        }
        return $res;
    }
    /**
     * 取消订单
     */
    public function cancelOrder($params = []) {
        $supplier_dsn = $params['supplierOrder']['supplier_dsn'];
        //先查询订单是否反馈成功，成功走售后，不成功走取消
        $data =[
            'sign'          => $this->config['sign'],
            'name'          => $this->config["account"],
            'pwd'           => $this->config["password"],
            'order_sn'      => $supplier_dsn,
            'page'          => 1,
        ];
        $requestParam = [
            'method'    => 'queryOrder',
            'data'      => $data
        ];
        $res = $this->inventoryExecute($requestParam);
        if($res["code"] != Normal::SUC){
            return Normal::returnCode(Normal::FAIL,"售后失败【失败原因：".$res['msg']."】");
        }
        if(!isset($res["data"]["total"]) or $res["data"]["total"] == 0){
            return Normal::returnCode(Normal::FAIL,"售后失败【供应商系统里没有查到此订单，订单号：".$supplier_dsn."】");
        }
        
        $orderInfo = current($res["data"]["rows"]);
        $orderStatus = $orderInfo["status"];
        //订单状态 0：待付款 10：已付款 30：待配货 40：待反馈 50：反馈成功 60：反馈失败 70：待退货 80:已退货 90：待退款 100：已退款
        if(in_array($orderStatus,[70,80,90,100])){
            return Normal::returnCode(Normal::SUC,"售后成功");
        }
        if(in_array($orderStatus,[0,10,30,40,60])){
            $res = $this->applyCancelOrder($params);
        }else{
            $res = $this->addAfterSalesOrder($params);
        }
        return $res;
    }
    /**
     * 添加售后取消订单
     */
    public function applyCancelOrder($params = []) {
        $supplier_dsn = $params['supplierOrder']['supplier_dsn'];
        $data =[
            'sign'          => $this->config['sign'],
            'name'          => $this->config["account"],
            'pwd'           => $this->config["password"],
            'order_sn'      => $supplier_dsn,
            'qxyy'          => $params["order"]["exceptReason"],
        ];
        $requestParam = [
            'method'    => 'applyCancelOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    /**
     * 添加售后
     */
    public function addAfterSalesOrder($params = []) {
        $supplier_dsn = $params['supplierOrder']['supplier_dsn'];
        //先查询订单是否反馈成功，成功走售后，不成功走取消
        $data =[
            'sign'              => $this->config['sign'],
            'order_id'          => $params["supplierOrder"]["thirdpart_order_sn"],
            'problem_type'      => "无理由退货",
            'problem_content'   => $params["order"]["exceptReason"],
        ];
        $requestParam = [
            'method'    => 'addAfterSalesOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 查询物流单信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $data =[
            'sign'          => $this->config['sign'],
            'name'          => $this->config["account"],
            'pwd'           => $this->config["password"],
            'order_sn'      => $param['order_sn'],
        ];
        $requestParam = [
            'method'    => 'getOrderFeedBackList',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 查询商品信息
     */
    public function queryGoodsList($param)
    {
        //获取商品列表
        $goodsWhere = [
            'sign'      => $this->config["sign"],
            'page'      => $param['page']  ?? 1,
            'rows'      => '10',//$param['limit']  ?? 50,
        ];
        $requestParam = [
            'method'    => 'queryGoodsList',
            'data'      => $goodsWhere,
        ];
        $res  = $this->execute($requestParam);
        if($res["code"] != Normal::SUC or !isset($res["data"]["rows"]) or empty($res["data"]["rows"])){
            return $res;
        }
        $result_query_goods = $res["data"]["rows"];
        $details = [];
        $selfSellTypeSkip = [];
        $wg = new WaitGroup();
        $count = count($result_query_goods);
        $wg->add($count);
        foreach ($result_query_goods as $sku)
        {
            co(function () use ($wg,$sku,&$selfSellTypeSkip, & $details)
            {
                $describe       = '';
                $title          = '';
                $commodityKey   = '';
                $barCodeList    = [];
                $goodsSpec      = [];
                //查询库存和价格信息,如果没有库存和价格，就不要
                $inventoryResponseParam = $this->queryInventoryList($sku);
                if ($inventoryResponseParam['code']== Normal::SUC && isset($inventoryResponseParam['data']["rows"]) && !empty($inventoryResponseParam['data']["rows"])){

                    //查询商品详情
                    $detailResponseParam = $this->queryGoodsDetail($sku["articleno"]);
                    if ( $detailResponseParam['code']== Normal::SUC && isset($detailResponseParam['data']["data"]) && $detailResponseParam['data']["data"]){
                        $describe = isset($detailResponseParam["data"]["data"]["describe"]) ? $detailResponseParam["data"]["data"]["describe"] : '';
                        $title    = $detailResponseParam["data"]["data"]["title"];
                    }
                    
                    //获取库存信息
                    $inventoryInfo = $inventoryResponseParam['data']["rows"];
                    foreach ($inventoryInfo as $i =>$inventory){
                        //获取市场价：marketprice*discount/10，四舍五入
                        $marketprice = bcmul($inventory["marketprice"],$inventory["discount"],2);
                        $marketprice = $marketprice >0 ? bcdiv($marketprice,10,2) : 0 ;
                        $marketprice = ceil($marketprice);
                        //组装数据
                        $details[]= [
                            'articleno'     => $sku["articleno"],//商品货号
                            'descr'         => $describe ??$sku["descr"],//商品描述信息
                            'cate'          => $inventory["cate"],//商品三级分类
                            'brandname'     => $sku["brandname"],//品牌
                            'marketprice'   => $marketprice,
                            'name'          => $sku["name"],
                            'barCode'       => $sku["articleno"],
                            'pic_url'       => isset($inventory["pic_url"]) ? $inventory["pic_url"] : '',
                            'title'         => $title ? $title." ".$inventory["size"] : $sku["title"]." ".$inventory["size"],
                            'size'          => $inventory["size"],
                            'wareHouseName' => $inventory["wareHouseName"],
                            'ukSize'        => $inventory["ukSize"],
                            'innerNum'      => $inventory["innerNum"],
                            'stock_id'      => $inventory["stock_id"],
                        ];
                    }
                }else {
                    $selfSellTypeSkip[] = 1;
                }
                $wg->done();
            });
        }
        $wg->wait();
        if( empty($details) && !empty($selfSellTypeSkip) && !empty($result_query_goods)) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'data'      => [],
                'has_next'  => true
            ]);
        }
        
        if( empty($details) && empty($selfSellTypeSkip) ) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'data'      => [],
                'has_next'  => false
            ]);
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'data'      => $details,
            'has_next'  => true
        ]);
        
    }

    /**
     * 查询商品详情
     */
    public function queryGoodsDetail($goods_no)
    {
        //查询商品详情
        $detailsWhere = [
            'sign'      => $this->config['sign'],
            'goods_no'  => $goods_no,
        ];
        $requestParam = [
            'method'    => 'queryGoodsDetail',
            'data'      => $detailsWhere,
        ];
        $responseParam = $this->execute($requestParam);
        return $responseParam;
         
    }
    /**
     * 查询商品库存
     */
    public function queryInventoryList($sku)
    {
        $inventoryWhere = [
            'sign'          => $this->config['sign'],
            'articleno'     => $sku["articleno"],
            'return_type'   => 1,//货源是否支持退货，1：支持退货 2：不支持退货
        ];
        $requestParam = [
            'method'    => 'queryInventoryList',
            'data'      => $inventoryWhere,
        ];
        $responseParam = $this->inventoryExecute($requestParam);
        return $responseParam;
         
    }
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function createOrderExecute( $param = [] ){
    
        $method = $param["method"];
        $url    = $this->config["baseurl"].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'    => 'Shoptianma_' . $method,
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $param['data'],
                'method' => "post",
                'format' => '',
                'header' => []
            ]
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (isset($result[0]['status']) && $result[0]['status'] == 0) {
            return Normal::returnCode(Normal::SUC, "OK",$result);
        }
        $message = isset($result[0]['info']) ? $result[0]["info"] : "";
        $message = $message ?? $resTask["error_info"];
        $message = $message ?? '操作失败';
        return Normal::returnCode(Normal::FAIL, $message);
    }
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] ){
        
        $method = $param["method"];
        $url    = $this->config["baseurl"].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'    => 'Shoptianma_' . $method,
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $param['data'],
                'method' => "post",
                'format' => '',
                'header' => []
            ]
        ];
        if( in_array($method,['queryGoodsList','queryGoodsDetail']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (!isset($result['error_code']) or $result['error_code'] == 0) {
            return Normal::returnCode(Normal::SUC, "OK",$result);
        }
        $message = $result['error_info'] ?? '操作失败';
        return Normal::returnCode(Normal::FAIL, $message);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function barCodeExecute( $param = [] ){
    
        $method = $param["method"];
        $url    = $this->config["baseurl"].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'    => 'Shoptianma_' . $method,
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $param['data'],
                'method' => "post",
                'format' => '',
                'header' => []
            ]
        ];
        $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (isset($result['status']) && $result['status'] == 0) {
            return Normal::returnCode(Normal::SUC, "OK",$result);
        }
        $message = $result['msg'] ?? '操作失败';
        return Normal::returnCode(Normal::FAIL, $message);
    }
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function inventoryExecute( $param = [] ){
    
        $method = $param["method"];
        $url    = $this->config["baseurl"].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'    => 'Shoptianma_' . $method,
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $param['data'],
                'method' => "post",
                'format' => '',
                'header' => []
            ]
        ];
        $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (isset($result['total'])) {
            return Normal::returnCode(Normal::SUC, "OK",$result);
        }
        $message = $result['msg'] ?? '操作失败';
        return Normal::returnCode(Normal::FAIL, $message);
    }
}